<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from '@/utils/message'
import { FormInstance } from 'element-plus'
import { addDept, updateDept } from '@/api/system/dept'
import { useDicts } from '@/utils/dict'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
  },
  deptOptions: {
    type: Array,
  },
  data: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const title = ref(props.title)
const deptOptions = ref(props.deptOptions)
const ruleFormRef = ref<FormInstance>()
const formVisible = ref(false)
const formData = ref(props.data)
const { sys_normal_disable } = useDicts('sys_normal_disable')

/** 提交按钮 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      if (formData.value.deptId != undefined) {
        updateDept(formData.value).then((_) => {
          message('提交成功', { type: 'success' })
          emit('refresh')
          formVisible.value = false
          resetForm(formEl)
        })
      } else {
        addDept(formData.value).then((_) => {
          message('新增成功', { type: 'success' })
          emit('refresh')
          formVisible.value = false
          resetForm(formEl)
        })
      }
    }
  })
}

/** 重置表单 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const closeDialog = () => {
  formVisible.value = false
  resetForm(ruleFormRef.value)
}

const emit = defineEmits(['update:visible', 'refresh'])
watch(
  () => formVisible.value,
  (val) => {
    emit('update:visible', val)
  }
)

watch(
  () => props.visible,
  (val) => {
    formVisible.value = val
  }
)

watch(
  () => props.title,
  (val) => {
    title.value = val
  }
)

watch(
  () => props.deptOptions,
  (val) => {
    deptOptions.value = val
  }
)

watch(
  () => props.data,
  (val) => {
    formData.value = val
  }
)

const rules = {
  parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  email: [
    {
      required: true,
      pattern:
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
}
</script>

<template>
  <el-dialog
    v-model="formVisible"
    :title="title"
    :width="680"
    draggable
    :before-close="closeDialog"
  >
    <!-- 表单内容 -->
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="100px">
      <el-row>
        <el-col v-if="formData.parentId !== 0" :span="24">
          <el-form-item label="上级部门" prop="parentId">
            <el-tree-select
              v-model="formData.parentId"
              :data="deptOptions"
              :props="{
                value: 'deptId',
                label: 'deptName',
                children: 'children',
              }"
              value-key="deptId"
              placeholder="选择上级部门"
              check-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number v-model="formData.orderNum" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="formData.leader" placeholder="请输入负责人" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系电话" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态">
            <el-radio-group v-model="formData.status">
              <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
                dict.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
    </template>
  </el-dialog>
</template>
